import React, {useState, useRef, useEffect} from 'react';
import {Button, Divider, message, Drawer, Modal, Table, Space, Spin, Descriptions} from 'antd';
import {PlusOutlined, ExclamationCircleOutlined, SyncOutlined} from '@ant-design/icons';
import {ColumnsType} from "antd/lib/table";
import styles from './index.module.scss';
import {ProductItem} from "@/common/interfaces/product";
import {IParam} from "@/common/common";
import {queryDept} from "@/apis/dept";
import {queryProduct} from "@/apis/product";
import UpdateProductForm from "@/pages/pms/product/components/UpdateProductForm";
import CreateProductForm from "@/pages/pms/product/components/CreateProductForm";

const TableList: React.FC<any> = () => {

  const [row, setRow] = useState<ProductItem>();
  const [stepFormValues, setStepFormValues] = useState({});

  const [loading, setLoading] = useState<boolean>(false)
  const [selectedRowsState, setSelectedRows] = useState<ProductItem[]>([]);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [params, setParams] = useState<IParam>({page: 1, size: 10});
  const [pageResponse, setPageResponse] = useState<any>({pageInfo: {page: 1, size: 10, total: 0}})

  useEffect(() => {
    setLoading(true)
    queryProduct({}, true).then(res => {
      setPageResponse(res)
    }).finally(() => setLoading(false))
  }, [params]);

  const showDeleteConfirm = (ids: number[]) => {
    Modal.confirm({
      title: "确认删除已选中的任务吗？",
      content: '删除的记录不能恢复,请谨慎操作!',
      icon: <ExclamationCircleOutlined/>,
      onOk() {
        // handleRemoveOne(id).then((r) => {
        //   actionRef.current?.reloadAndRest?.();
        // });
      }
    });
  };

  const columns: ColumnsType<any> = [
    {
      title: '商品名',
      key: 'name',
      dataIndex: 'name',
      align: "center",
      render: (value, record) => {
        return <a onClick={() => setRow(record)}>{value}</a>;
      },
    },
    {
      title: '促销价格',
      key: 'promotionPrice',
      dataIndex: 'promotionPrice',
      align: "center",
    },
    {
      title: '赠送的成长值',
      key: 'giftGrowth',
      dataIndex: 'giftGrowth',
      align: "center",
    },
    {
      title: '赠送的积分',
      key: 'giftPoint',
      dataIndex: 'giftPoint',
      align: "center",
    },
    {
      title: '市场价',
      key: 'originalPrice',
      dataIndex: 'originalPrice',
      align: "center",
    },
    {
      title: '库存',
      key: 'stock',
      dataIndex: 'stock',
      align: "center",
    },
    {
      title: '品牌名称',
      key: 'brandName',
      dataIndex: 'brandName',
      align: "center",
    },
    {
      title: '商品分类名称',
      key: 'productCategoryName',
      dataIndex: 'productCategoryName',
      align: "center",
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      align: "center",
      render: (_, record) => (
        <>
          <Button
            type="primary"
            size="small"
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            编辑
          </Button>
          <Divider type="vertical"/>
          <Button
            type="primary"
            danger
            size="small"
            onClick={() => {
              showDeleteConfirm([record.id]);
            }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  const renderToolBar = () => {
    return (
      <Space size={10}>
        <Button type="primary" onClick={() => handleModalVisible(true)}>
          新增
        </Button>
        <Button
          onClick={() => handleModalVisible(true)}>
          删除
        </Button>
        <Button type="dashed">
          <SyncOutlined/>
        </Button>
        {`共${pageResponse.pageInfo.total}条记录`}
      </Space>
    )
  }

  return (
    <div className={styles.container}>
      <div className={styles.toolBar}>{renderToolBar()}</div>
      <Spin spinning={loading}>
        <Table
          rowKey={"id"}
          columns={columns}
          dataSource={pageResponse.data || []}
          pagination={{
            current: pageResponse.pageInfo.page || 0,
            pageSize: pageResponse.pageInfo.size || 10,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ["10", "20", "30"],
            total: pageResponse.pageInfo.total || 0,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (pageNo, pageSize) => {
              setParams({...params, ...{page: pageNo, size: pageSize}})
            }
          }}
        />
      </Spin>

      <CreateProductForm
        key={'CreateProductForm'}
        onSubmit={async (value) => {
          handleModalVisible(false);
          setStepFormValues({});
          // const success = await handleAdd(value);
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        createModalVisible={createModalVisible}
      />

      <UpdateProductForm
        key={'UpdateProductForm'}
        onSubmit={async (value) => {
          // const success = await handleUpdate(value);
          handleUpdateModalVisible(false);
          setStepFormValues({});
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setStepFormValues({});
        }}
        updateModalVisible={updateModalVisible}
        currentData={stepFormValues}
      />

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.id && (
          <Descriptions title="基本信息" bordered column={2} style={{margin: '20px 0 20px 20px', height: '400px'}}>
            {columns.map((item) => {
              return (
                <Descriptions.Item label={item.key}>
                  {item.key || ''}
                </Descriptions.Item>
              )
            })}
          </Descriptions>
        )}
      </Drawer>
    </div>
  )
}

export default TableList
